<template>
  <div>
    <!-- 热门搜索 -->
    <van-search
      @input="onSearchInput"
      shape="round"
      v-model="value"
      placeholder="请输入搜索关键词"
    />
    <template v-if="value === ''">
      <van-cell title="热门搜索" />
      <div style="padding: 10px 16px">
        <van-tag
        v-for="item in hots" :key="item.first"
        @click="onTag(item.first)"
        plain color="red" round size="large" type="primary"
          >{{item.first}}</van-tag
        >
      </div>
    </template>

    <template v-else>
      <!-- 最佳匹配 -->
      <van-cell title="最佳匹配" />
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="亲，没有数据了呦！"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        :immediate-check="false"
      >
       <music-item  v-for="item in list"
          :key="item.id"
          :title="item.name"
          :row="item">
          </music-item>
      </van-list>
    </template>
  </div>
</template>

<script>
import { getSearchList, getHotList } from '@/api/search'
import { Toast } from 'vant'
import MusicItem from '@/components/MusicItem/index'

export default {
  name: 'search',
  components: {
    MusicItem
  },
  data () {
    return {
      value: '',
      list: [],
      loading: false,
      finished: false,
      page: 1,
      limit: 20,
      error: false,
      songCount: 0,
      hots: []
    }
  },

  created () {
    this.getHotList()
  },

  methods: {
    onSearchInput () {
      this.list = []
      this.finished = false
      this.page = 1
      clearTimeout(this.id)
      this.loading = true
      if (this.value === '') return
      this.id = setTimeout(_ => {
        this.onLoad()
      }, 700)
    },
    // 搜索结果
    async onLoad () {
      console.log('加载数据')
      // 什么时候触发加载数据
      // 1页面一进入 在可视区域内显示list
      // onload加载后获取数据展示到页面 没有沾满一屏
      // 3即将触底时加载数据

      // 过程
      // 1模拟请求数据
      // 2保存数据

      try {
        const res = await getSearchList({
          keywords: this.value,
          limit: this.limit,
          offset: (this.page - 1) * this.limit
        })
        if (res.data.result.songs) {
          this.songCount = res.data.result.songCount
          this.list.push(...res.data.result.songs)
          this.page++
        } else {
          this.songCount = 0
        }
      } catch (err) {
        // Toast.fail('获取数据失败')
        this.error = true
      }
      // 3加载状态结束
      this.loading = false
      // 4数据全部加载完成时刷新
      if (this.list.length >= this.songCount) {
        this.finished = true
      }
    },
    async getHotList () {
      try {
        const res = await getHotList()
        this.hots = res.data.result.hots
      } catch (err) {
        Toast('获取数据失败')
      }
    },
    onTag (item) {
      this.value = item
      // 调用搜索框改变的事件
      this.onSearchInput()
    }
  }
}
</script>

<style scoped lang="less"></style>
